﻿var extend = function(destination, source)
{
	for (var property in source)
	{
		destination[property] = source[property];
	}
	return destination;
};

function shorten(settings)
{
	var config = {
		showChars: 200,
		ellipsesText: "...",
		moreText: SSVC.Utils.GetResource("short_more"),
		lessText: SSVC.Utils.GetResource("short_less"),
		classToShorten: "MessageText"
	};

	if (settings)
	{
		extend(config, settings);
	}

	SSVC.Wrap.Dojo.Query(".morelink").forEach(function(node)
	{
		node.onclick = function()
		{
			var dnode = new SSVC.Wrap.Dojo.DojoNode(node);
			if (SSVC.Wrap.Dojo.HasClass(node, "less"))
			{
				SSVC.Wrap.Dojo.RemoveClass(node, "less");
				node.innerHTML = config.moreText;
				dnode.parent().prev().style("display", "inline");
				dnode.prev().style("display", "none");
			}
			else
			{
				SSVC.Wrap.Dojo.AddClass(node, "less");
				node.innerHTML = config.lessText;
				dnode.parent().prev().style("display", "none");
				dnode.prev().style("display", "inline");
			}
		};
	});

	return SSVC.Wrap.Dojo.Query("." + config.classToShorten).forEach(function(node)
	{
		if (SSVC.Wrap.Dojo.HasClass(node, "shortened")) return;

		SSVC.Wrap.Dojo.AddClass(node, "shortened");
		var content = node.innerHTML;
		if (content.length > config.showChars)
		{
			var c = content.substr(0, config.showChars);
			var h = content.substr(config.showChars, content.length - config.showChars);
			var html = c + "<span class='moreellipses'>" + config.ellipsesText + " </span><span class='morecontent'><span>" +
				h + "</span><a href='#' class='morelink'>" + config.moreText + "</a></span>";
			node.innerHTML = html;
			SSVC.Wrap.Dojo.Query(".morecontent span").style("display", "none");
		}
	});

}

SSVC.Wrap.Dojo.SetObject("SSVC.Utils.Shorten", shorten);